package cn.itcast.crm.service.impl;

import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.transaction.annotation.Transactional;

import cn.itcast.crm.dao.CustomerRepository;
import cn.itcast.crm.domain.Customer;
import cn.itcast.crm.service.CustomerService;

@Service
@Transactional
public class CustomerServiceImpl implements CustomerService{
	
	@Autowired
	CustomerRepository customerRepository;
	
	/**查询所有未关联客户列表，即字段fixedAreaId is null*/
	@Override
	public List<Customer> findNoAssociationCustomers() {
		// fixedAreaId is null
		return customerRepository.findByFixedAreaIdIsNull();
	}
	
	/**将客户关联到定区上 ， 将所有客户id 拼成字符串 1,2,3，使用客户ID更新客户，更新fixedAreaId字段*/
	@Override
	public List<Customer> findHasAssociationFixedAreaCustomers(String fixedAreaId) {
		// 解除关联动作，将该定区ID的所有用户全部置null
		return customerRepository.findByFixedAreaId(fixedAreaId);
	}

	@Override
	public void associationCustomersToFixedArea(String customerIdStr, String fixedAreaId) {
		// 解除关联动作，将该定区ID的所有用户全部置null
		customerRepository.clearFixedAreaId(fixedAreaId);
		
		// 切割字符串 1,2,3，组织新的关联关系
		if(StringUtils.isBlank(customerIdStr)){
			return;
		}
		String [] customerIdArray = customerIdStr.split(",");
		for (String customerId : customerIdArray) {
			customerRepository.updateFixedAreaId(fixedAreaId, Integer.parseInt(customerId));
		}
	}

	@Override
	public List<Customer> customer_findAssociation(String fixedAreaId) {
		
		return customerRepository.findByFixedAreaId(fixedAreaId);
	}

	/**
	 * 用户注册
	 * */
	@Override
	public void regist(Customer customer) {
		customerRepository.save(customer);
	}

	//使用手机号查询激活状态
	@Override
	public Customer activeMail(String telephone) {
		return customerRepository.findByTelephone(telephone);
	}

	//使用手机号查询更改激活状态
	@Override
	public void customer_updateType(String telephone) {
		customerRepository.updateType(telephone);
		
	}
	//用户登陆
	@Override
	public Customer login(String telephone, String password) {
		return customerRepository.findByTelephoneAndPassword(telephone,password);
	}

	//通过客户ID和寄件人地址获取定区ID
	@Override
	public String findFixAreaIdByAddressAndID(Integer customerId, String sendAddress) {
		return customerRepository.findFixAreaIdByAddressAndID(sendAddress,customerId);
	}
}
